package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类维护所有请求与对应的业务处理类的关系
 */
public class HandlerMapping {
    /*
    key: 请求路径
    value: 处理该请求的Controller和对应的业务方法
     */
    public static Map<String,MethodMapping> mapping=new HashMap<>();

    static {
        initMapping();
    }

    public static void initMapping(){
        try {
            File dir=new File(
                    HandlerMapping.class.getClassLoader().getResource("./com/webserver/controller").toURI()
            );
            File[] files=dir.listFiles(f->f.getName().endsWith(".class"));
            for (File file:files){
                Class cls=Class.forName("com.webserver.controller."+file.getName().substring(0,file.getName().lastIndexOf(".")));
                if (cls.isAnnotationPresent(Controller.class)){
                    Object obj=cls.newInstance();
                    Method[] methods=cls.getDeclaredMethods();
                    for (Method method:methods){
                        if (method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping rem=method.getAnnotation(RequestMapping.class);
                            String value=rem.value();
                            mapping.put(value,new MethodMapping(obj,method));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据给定的请求路径获取处理该请求的Controller及对应的业务方法
     * @param path
     * @return
     */
    public static MethodMapping getMethod(String path){
        return mapping.get(path);
    }
    public static class MethodMapping{
        private Object controller;
        private Method method;

        public MethodMapping() {
        }

        public MethodMapping(Object controller, Method method) {
            this.controller = controller;
            this.method = method;
        }

        @Override
        public String toString() {
            return "MethodMapping{" +
                    "controller=" + controller +
                    ", method=" + method +
                    '}';
        }

        public Object getController() {
            return controller;
        }

        public Method getMethod() {
            return method;
        }
    }

    public static void main(String[] args) {
        System.out.println(mapping);
        MethodMapping mm=mapping.get("/myweb/reg");
        System.out.println();
        System.out.println(mm);
    }
}
